package com.patent.service.impl;

import com.patent.common.DateUtil;
import com.patent.common.PatentConstant;
import com.patent.common.ResultCode;
import com.patent.common.ResultData;
import com.patent.common.SmsUtil;
import com.patent.domain.po.AuthCodeInfo;
import com.patent.service.AuthCodeService;
import com.patent.service.SmsService;
import com.patent.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Map;

@Service("smsService")
@Transactional
public class SmsServiceImpl implements SmsService {

	private static final Logger log = LoggerFactory.getLogger(SmsServiceImpl.class);

	@Resource(name="userService")
	private UserService userService;

	@Resource(name="authCodeService")
	private AuthCodeService authCodeService;

	@Override
	public ResultData sendAuthCode(String userMobile) {
		ResultData resultData = new ResultData();
		/*//验证手机号是否注册过
		User user = userService.selectByUserMobile(userMobile);
		if(user != null){
			resultData.setCode(ResultCode.repeatError.getCode());
			resultData.setMsg("此用户已注册过");
			return resultData;
		}*/
		//查询用户是否在一分钟之内发过验证码
		AuthCodeInfo queryAuthCodeInfo = authCodeService.queryAuthCodeInfo(userMobile);
		if(queryAuthCodeInfo != null){
			Date createDate = queryAuthCodeInfo.getCreateDate();
			int second = DateUtil.getTimeDelta(createDate,new Date());
			log.info("queryAuthCodeInfo second:"+second);
			if(second <= 60){
				resultData.setCode(ResultCode.alreadySendCode.getCode());
				resultData.setMsg("一分钟之内已发送过验证码，请勿重复发送");
				return resultData;
			}else{
				resultData = sendAndSaveAuthCode(userMobile);
			}
		}else{
			//发送短信，存入数据库
			resultData = sendAndSaveAuthCode(userMobile);
		}
		return resultData;
	}

	private ResultData sendAndSaveAuthCode(String userMobile){
		ResultData resultData = new ResultData();
		try {
			Map<String,Object> map = SmsUtil.sendMsg(userMobile, PatentConstant.activeTime);
			String authCode = (String) map.get("authCode");
			String errMsg = (String) map.get("errMsg");
			if(StringUtils.isNotBlank(authCode)){
				AuthCodeInfo saveAuthCodeInfo = new AuthCodeInfo();
				saveAuthCodeInfo.setAuthCode(authCode);
				saveAuthCodeInfo.setUserMobile(userMobile);
				authCodeService.insertSelective(saveAuthCodeInfo);
				resultData.setCode(ResultCode.success.getCode());
				resultData.setMsg(ResultCode.success.getMessage());
			}else{
				resultData.setCode(ResultCode.sendFailCode.getCode());
				resultData.setMsg(errMsg);
			}
		} catch (Exception e) {
			resultData.setCode(ResultCode.sendFailCode.getCode());
			resultData.setMsg("发送短信验证码失败");
		}
		return resultData;
	}

}
